<?php
namespace app\admin\controller;

use app\admin\service\TokenService;
use app\admin\service\UserService;
use app\admin\util\StringUtil;
use app\admin\validate\user\UserValidate;
use app\BaseController;
use think\App;
use think\captcha\facade\Captcha;
use think\db\exception\DbException;
use think\exception\ValidateException;
use think\facade\Cookie;
use think\facade\View;
use think\Response;
use think\response\Json;

class User extends BaseController
{
    protected $request;
    protected $service;
    protected $tokenService;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->service = app()->make(UserService::class);
        $this->tokenService = app()->make(TokenService::class);
    }


    /**
     * 登录页
     *
     * @return string
     */
    public function login(): string
    {
        // 模板输出
        return View::fetch('login');
    }

    /**
     * 退出
     *
     * @return string
     */
    public function logout(): Response
    {
        Cookie::delete("token");
        Cookie::delete("nickname");
        return redirect("/admin/user/login");
    }

    /**
     * 登录校验
     *
     * @return Json
     */
    public function doLogin(): Json
    {
        $data['captcha'] = $this->request->post("captcha");
        $data['username'] = $this->request->post("username");
        $data['password'] = $this->request->post("password");
        try {
            validate(UserValidate::class)
                ->scene('login')
                ->check($data);
        } catch (ValidateException $error) {
            // 验证失败 输出错误信息
            return error(1,$error->getError());
        }
        if(!captcha_check($data['captcha']))
        {
            return error(501,  '验证码不正确');
        }
        try {
            $user = $this->service->doLogin($data['username'], $data['password']);
            if ($user == null) {
                return error(502,  '用户名或者密码不正确');
            }
            $token = $this->tokenService->queryToken($user->id);
            Cookie::set("token", $token);
            Cookie::set("nickname", $user->nickname);
            return success($token);
        } catch (DbException $e) {
            return error(500,  '服务异常，请稍后重试');
        }
    }

    /**
     * @return Response
     */
    public function captcha(): Response
    {
        return Captcha::create();
    }

    /**
     * 修改密码
     * @return string
     */
    public function password(): string
    {
        // 模板输出
        return View::fetch('password');
    }

    public function doPassword(): Json
    {
        try {
            validate(UserValidate::class)
                ->scene('editPassword')
                ->check($this->request->post());
        } catch (ValidateException $error) {
            // 验证失败 输出错误信息
            return error(1,$error->getError());
        }
        $user = $this->service->queryUser();
        $newPassword = StringUtil::getPassword($this->request->post("newPassword"), $user['salt']);
        if (!$this->service->checkPassword($user, $this->request->post("oldPassword"))) {
            return error(503, '旧密码不正确');
        }
        $data['password'] = $newPassword;
        $where['id'] = $user['id'];
        return success($this->service->updateUser($data, $where));
    }
}

